package cn.tedu.jxc.service.impl;

import cn.tedu.jxc.ex.ServiceException;
import cn.tedu.jxc.mapper.CategoryMapper;
import cn.tedu.jxc.pojo.dto.CategoryDTO;
import cn.tedu.jxc.pojo.entity.Category;
import cn.tedu.jxc.pojo.vo.CategoryListItemVO;
import cn.tedu.jxc.pojo.vo.CategoryStandardVO;
import cn.tedu.jxc.pojo.vo.CategoryTreeListVO;
import cn.tedu.jxc.repo.CategoryRedisRepository;
import cn.tedu.jxc.service.CategoryService;
import cn.tedu.jxc.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;


    @Override
    public List<CategoryTreeListVO> list() {
        List<CategoryTreeListVO> treeList = categoryMapper.getTreeList();
        return treeList;
    }

    @Override
    public List<CategoryTreeListVO> treeList(Long parentId) {
        return categoryMapper.getListByParentId(parentId);
    }

    @Override
    public List<CategoryListItemVO> getList(Long prentId) {
        return categoryMapper.getList(prentId);
    }

    @Override
    public List<CategoryListItemVO> search(String categoryName) {
        return categoryMapper.search(categoryName);
    }

    @Override
    public CategoryStandardVO getById(Long id) {
        CategoryStandardVO categoryStandardVO = categoryMapper.selectById(id);
        if (categoryStandardVO == null) {
            String message = "类别不存在!";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return categoryStandardVO;

    }

    @Override
    public void addNew(CategoryDTO categoryDTO) {

        Integer depth = 1;
        Long parentId = categoryDTO.getParentId();
        CategoryStandardVO parentCategory = null;
        if (parentId != 0) {
            // 确定当前类别的depth值，为：父级depth + 1
            parentCategory = categoryMapper.selectById(parentId);
            log.debug("根据父级类别ID【{}】查询父级类别详情，结果：{}", parentId, parentCategory);
            if (parentCategory == null) {
                String message = "添加类别失败，所选择的父级类别不存在！";
                log.debug(message);
                throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
            }
            depth = parentCategory.getDepth() + 1;
        }
        log.debug("当前尝试添加的类型的depth值为：{}", depth);


        String name = categoryDTO.getName();
        CategoryStandardVO categoryStandardVO = categoryMapper.selectByName(name);

        if (categoryStandardVO !=null) {
            String message = "添加类别失败，尝试添加的类别名称【" + name + "】已经存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        category.setDepth(depth);
        category.setIsParent(0);
        log.debug("准备向数据库中写入类别数据：{}", category);
        int rows = categoryMapper.insert(category);
        if (rows != 1) {
            String message = "添加类别失败，服务器忙，请稍后再尝试！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }

        if (parentId != 0) {
            if (parentCategory.getIsParent() == 0) {
                Category updateParentCategory = new Category();
                updateParentCategory.setId(parentId);
                updateParentCategory.setIsParent(1);
                log.debug("将父级类别的isParent更新为1，更新的参数对象：{}", updateParentCategory);
                rows = categoryMapper.updateById(updateParentCategory);
                if (rows != 1) {
                    String message = "添加类别失败，服务器忙，请稍后再尝试！";
                    log.debug(message);
                    throw new ServiceException(ServiceCode.ERR_UPDATE, message);
                }
            }
        }
    }

    @Override
    public void enable(Long categoryId) {
        setEnable(categoryId,1);
    }

    @Override
    public void disable(Long categoryId) {
        setEnable(categoryId,0);
    }

    @Override
    public void delete(Long id) {
        CategoryStandardVO categoryStandardVO = categoryMapper.selectById(id);
        if (categoryStandardVO == null) {
            String message = "类别删除，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        Integer isParent = categoryStandardVO.getIsParent();
        if (isParent==1){
            String message = "类别删除，当前类别存在子类别！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        int rows = categoryMapper.deleteById(id);
        if (rows != 1) {
            String message = "删除类别失败，服务器忙，请稍后再尝试！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        log.debug("类别删除成功!");
    }

    private void setEnable(Long id,Integer enable ){
        System.out.println(enable);
        String[] tips = {"禁用", "启用"};
        log.debug("开始处理【{}类别】的业务，参数：{}", tips[enable], id);

        CategoryStandardVO queryResult = categoryMapper.selectById(id);
        if (queryResult == null) {
            String message = tips[enable] + "类别失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        if (queryResult.getEnable().equals(enable)) {
            String message = tips[enable] + "类别失败，当前类别已经处于" + tips[enable] + "状态！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        Category category = new Category();
        category.setId(id);
        category.setEnable(enable);
        int rows = categoryMapper.updateById(category);
        if (rows != 1) {
            String message = tips[enable] + "类别失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        log.debug("类别"+tips[enable]+"成功！");
    }
}
